﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Xml.Linq;
using VisualWip.Core;
using VisualWip.Core.Interfaces;
using VisualWip.Util;

namespace VisualWip.FilePersistanceProvider
{
    [Export(typeof(IPersistanceProvider))]
    public class FilePersistanceProvider : IPersistanceProvider
    {
        private readonly IPersistanceTreeSerializer _serializer;

        [ImportingConstructor]
        public FilePersistanceProvider(IPersistanceTreeSerializer serializer)
        {
            _serializer = serializer;
        }

        #region IPersistanceProvider Members

        public string Name
        {
            get { return "File system persistance provider"; }
        }

        public bool IsSettingsPathSupported(ISettingsPath settingsPath)
        {
            return settingsPath is FileSettingsPath;
        }

        public void Persist(ISettingsPath settingsPath, PersistenceTree persistenceTree)
        {
            if(!settingsPath.HasPath)
                throw new FileNotFoundException(string.Format("The settings file path: {0} is not valid.", settingsPath.Path), settingsPath.Path);

            using (var x = new FileStream(settingsPath.Path, FileMode.Create))
            {
                _serializer.Save(x, persistenceTree);
            }
        }

        public PersistenceTree Load(ISettingsPath settingsPath)
        {
            if(!(settingsPath.HasPath && new FileInfo(settingsPath.Path).Exists))
                throw new FileNotFoundException(string.Format("The settings file path: {0} is not valid.", settingsPath.Path), settingsPath.Path);

            using (var x = new FileStream(settingsPath.Path, FileMode.Open))
            {
                return _serializer.Load(x);
            }
        }

        public PersistenceTree LoadFromPathString(string pathString)
        {
            return Load(new FileSettingsPath() {Path = pathString});
        }

        public IPathSelector PathSelector
        {
            get { return new FileDialogPathSelector(); }
        }

        #endregion
    }
}